import { useEnv } from '@/hooks/useEnv';
const { getEnv } = useEnv();

export const cdnImgHead = getEnv('CDN_IMG_HEAD');

/**
 * 获取文件服务器完整url地址
 * @export
 * @param {string} url
 * @return {*}
 */
export function getImgUrl(url: string): string {
  return cdnImgHead + url;
}

/**
 * 根据网络路径判断是否有本地缓存文件,有则返回,没有则缓存
 * @export
 * @param {string} url
 * @return url
 */
export function getFileStorage(url: string) {
  let lastUrl = url.replace(cdnImgHead,'');
  let fileKey = lastUrl.substring(0, lastUrl.indexOf('.'));
  const filePath = uni.getStorageSync(fileKey) ?? "";
  if(filePath){
    return filePath
  }else{
    // #ifndef H5
    uni.downloadFile({
      url,
      success: function(r) {
        if (r.statusCode === 200) {
          const fs = uni.getFileSystemManager();
          fs.saveFile({
            tempFilePath: r.tempFilePath,
            success(_res) {
              uni.setStorageSync(fileKey, _res.savedFilePath)
            }
          })
        }
      }
    })
    // #endif
    return url
  }
}

